﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using LogicWaveWpf.Common;
using System.Security.Cryptography.Xml;
using System.Dynamic;
using System.IO;
using CommunityToolkit.Mvvm.Input;
using System.Windows;

namespace LogicWaveWpf.ViewMode
{
    public partial class MainViewModel : ObservableObject
    {
        [ObservableProperty]
        public List<DataConfigInfo> datas = new List<DataConfigInfo>();

        [ObservableProperty]
        public int age = 100;

        [ObservableProperty]
        public string txtpath = DataConfigWpf.Properties.Settings.Default.txtpath;

        [ObservableProperty]
        public string jsonpath = DataConfigWpf.Properties.Settings.Default.jsonpath;

        public MainViewModel()
        {
            if (!File.Exists(txtpath))
            {
                MessageBox.Show($"txt文件{txtpath}不存在");
                return;
            }
            if (!File.Exists(jsonpath))
            {
                MessageBox.Show($"json文件{jsonpath}不存在");
                return;
            }

            var data = ConfigHelper.GetTxtData(txtpath);
            for (int i = 0; i < data.Count; i++)
            {
                var tn = data[i][0];
                var val = ConfigHelper.GetConfig<string>(jsonpath, tn);
                datas.Add(new DataConfigInfo { id = i + 1, name = tn, memo = data[i][1], value = val });
            }
            
        }

        [RelayCommand]
        public void SaveData()
        {
            if (datas.Count() <= 0) return;

            var ret = false;
            //List<dynamic> lst = new List<dynamic>();
            //dynamic expando = new ExpandoObject();
            var dict = new Dictionary<string, object>();

            datas.ForEach(c =>
            {
                //dict[c.Name] = c.Value; // 动态添加键值
                dict.Add(c.name, c.value);
            });
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented);
            using (StreamWriter sw = new StreamWriter(DataConfigWpf.Properties.Settings.Default.jsonpath, false, Encoding.UTF8))
            {
                sw.Write(json);
                ret = true;
            }
            MessageBox.Show($"配置保存{(ret ? "成功" : "失败")}");
        }
    }


    public class DataConfigInfo
    {
        public int id { get; set; }
        public string? name { get; set; }
        public string? memo { get; set; }
        public string? value { get; set; }
    }

}
